<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col :span="6">
          <el-button type="primary" @click="addOpen = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" stripe border>
        <el-table-column width="50px" type="expand">
          <template slot-scope="scope">
            <el-row :class="['vertical-center','bdBottom', index1 === 0? 'bdTop' : '']"  v-for="(item, index1) in scope.row.children" :key="item.id" >
              <el-col :span="5">
                <el-tag closable @close="deleteRight(item.id,scope.row)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row :class="['vertical-center',index2 === 0? '' : 'bdTop']" v-for="(item, index2) in item.children" :key="item.id">
                  <el-col :span="6">
                    <el-tag closable @close="deleteRight(item.id,scope.row)" type="success">{{item.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag v-for="(item, index3) in item.children" :key="item.id" closable @close="deleteRight(item.id,scope.row)" type="warning">{{item.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName" ></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc" ></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRoles(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRole(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="getRightsTree(scope.row)">修改权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="添加角色" :visible.sync="addOpen" width="50%" @close="resetForm('add')" :close-on-click-modal="false" >
      <el-form :model="addForm" :rules="addFormRules" label-width="80px" ref="addFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addOpen = false">取消</el-button>
        <el-button @click="addRoles">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改角色" :visible.sync="editOpen" width="50%" @close="resetForm('edit')" :close-on-click-modal="false" >
      <el-form :model="roleInfo" label-width="80px" :rules="addFormRules" ref="editFormRef">
        <el-form-item label=" id">
          <el-input v-model="roleInfo.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editOpen = false">取消</el-button>
        <el-button @click="editRole(roleInfo.roleId)">确认</el-button>
      </span>
    </el-dialog>
    <el-dialog title="分配权限" :visible.sync="showRightTree" width="50%" :close-on-click-modal="false">
      <el-tree :data="rightsTree" ref="treeRef" show-checkbox node-key="id" :default-checked-keys="keyId" default-expand-all :props="defaultProps">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRightTree = false">取消</el-button>
        <el-button @click="allotRights(roleId)">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      addOpen: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
        roleName: [
          { required: true, message: '请填写角色名称', trigger: 'blur' },
          { min: 2, max: 8, message: '请输入正确的角色名称', trigger: 'blur' }
        ]
      },
      editOpen: false,
      roleInfo: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      showRightTree: false,
      rightsTree: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      roleId: '',
      keyId: []
    }
  },
  methods: {
    async getRolesList() {
      const { data: response } = await this.$http.get('roles')
      if(response.meta.status !== 200) return this.$message({ type: 'error', message: '角色列表获取失败！', duration: 2000 })
      this.$message({ type: 'success', message: '角色列表获取成功！', duration: 2000 })
      this.rolesList = response.data
    },
    resetForm(type) {
      if(type === 'add') {
        return this.$refs.addFormRef.resetFields()
      }
      if(type === 'edit') {
        return this.$refs.editFormRef.resetFields()
      }
    },
    addRoles() {
      this.$refs.addFormRef.validate(async valid => {
        if(!valid) return
        const { data: response } = await this.$http.post('roles', this.addForm)
        if(response.meta.status !== 201) return this.$message({ type: 'error', message: '添加角色失败', duration: 2000 })
        this.$message({ type: 'success', message: '添加角色成功', duration: 2000 })
        this.addOpen = false
        this.getRolesList()
      })
    },
    editRoles(role) {
      this.editOpen = true
      this.roleInfo.roleId = role.id
      this.roleInfo.roleName = role.roleName
      this.roleInfo.roleDesc = role.roleDesc
    },
    editRole(id) {
      this.$refs.editFormRef.validate(async valid => {
        if(!valid) return
        const { data: response } = await this.$http.put('roles/' + id, { roleName: this.roleInfo.roleName, roleDesc: this.roleInfo.roleDesc })
        if(response.meta.status !== 200) return this.$message({ type: 'error', message: '修改角色失败', duration: 2000 })
        this.$message({ type: 'success', message: '修改角色成功', duration: 2000 })
        this.editOpen = false
        this.getRolesList()
      })
    },
    async deleteRole(id) {
      const flag = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if(flag !== 'confirm') return this.$message({ type: 'info', message: '已取消删除操作', duration: 2000 })
      const { data: response } = await this.$http.delete('roles/' + id)
      if(response.meta.status !== 200) return this.$message({ type: 'error', message: '删除失败', duration: 2000 })
      this.$message({ type: 'success', message: '删除成功', duration: 2000 })
      this.editOpen = false
      this.getRolesList()
    },
    async deleteRight(id, role) {
      const flag = await this.$confirm('确定删除该权限吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if(flag !== 'confirm') return this.$message({ type: 'info', message: '已取消删除权限操作', duration: 2000 })
      const { data: response } = await this.$http.delete(`roles/${role.id}/rights/${id}`)
      if(response.meta.status !== 200) return this.$message({ type: 'error', message: '修改权限失败', duration: 2000 })
      this.$message({ type: 'success', message: '取消权限成功', duration: 2000 })
      role.children = response.data
    },
    async getRightsTree(role) {
      this.keyId = []
      this.roleId = role.id
      const { data: response } = await this.$http.get('rights/tree')
      this.rightsTree = response.data
      this.getKeyId(role, this.keyId)
      this.showRightTree = true
    },
    getKeyId(node, arr) {
      if(!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getKeyId(item, arr))
    },
    async allotRights(id) {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keysStr = keys.join(',')
      const { data: response } = await this.$http.post(`roles/${id}/rights`, { rids: keysStr })
      if(response.meta.status !== 200) return this.$message({ type: 'error', message: '修改权限失败', duration: 2000 })
      this.$message({ type: 'success', message: '修改权限成功', duration: 2000 })
      this.getRolesList()
      this.showRightTree = false
    }
  },
  created() {
    this.getRolesList()
  }
}
</script>

<style lang="less" scoped>
  .bdTop {
    border-top: 1px solid #eee;
  }
  .bdBottom {
    border-bottom: 1px solid #eee;
  }
  .el-tag{
    margin: 7px;
  }
  .vertical-center{
    display: flex;
    align-items: center;
  }
</style>
